import { useForm } from 'react-hook-form';
import { useNavigate, Link } from '@tanstack/react-router';
import { Card, CardHeader, CardTitle, CardContent } from '../components/ui/card';
import { Button } from '../components/ui/button';
import Layout from '../components/Layout';
import { useCreatePostMutation, useUsersQuery } from '../hooks/useQueries';
import { useCurrentUser } from '../store/useStore';

interface CreatePostForm {
  title: string;
  body: string;
  userId: number;
}

export default function CreatePostPage() {
  const navigate = useNavigate();
  const currentUser = useCurrentUser();
  const { data: users } = useUsersQuery();
  const createPostMutation = useCreatePostMutation();

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    watch,
    setValue,
  } = useForm<CreatePostForm>({
    defaultValues: {
      title: '',
      body: '',
      userId: currentUser?.id || 1,
    },
  });

  const watchedTitle = watch('title');
  const watchedBody = watch('body');

  const onSubmit = async (data: CreatePostForm) => {
    try {
      await createPostMutation.mutateAsync(data);
      navigate({ to: '/posts' });
    } catch (error) {
      // Error handling is done in the mutation
      console.error('Failed to create post:', error);
    }
  };

  const fillSampleData = () => {
    setValue('title', 'Sample Post Title: Modern React Development');
    setValue('body', `This is a sample post demonstrating the power of modern React development with TypeScript, TanStack Query, and React Hook Form.

Here are some key features:
• Type-safe API interactions
• Optimistic updates with TanStack Query
• Form validation with React Hook Form
• State management with Zustand
• Beautiful UI with Tailwind CSS and Radix UI

The template includes comprehensive examples of how to build scalable React applications in 2025.`);
  };

  return (
    <Layout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div className="flex items-center gap-4">
          <Button asChild variant="outline">
            <Link to="/posts">← Back to Posts</Link>
          </Button>
          <h1 className="text-3xl font-bold">Create New Post</h1>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Form */}
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle>Post Details</CardTitle>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                  {/* User Selection */}
                  <div className="space-y-2">
                    <label htmlFor="userId" className="text-sm font-medium">
                      Author
                    </label>
                    <select
                      id="userId"
                      {...register('userId', {
                        required: 'Please select an author',
                        valueAsNumber: true,
                      })}
                      className="w-full px-3 py-2 border border-input bg-background rounded-md text-sm ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      {users?.map((user) => (
                        <option key={user.id} value={user.id}>
                          {user.name} (@{user.username})
                        </option>
                      ))}
                    </select>
                    {errors.userId && (
                      <p className="text-sm text-destructive">{errors.userId.message}</p>
                    )}
                  </div>

                  {/* Title */}
                  <div className="space-y-2">
                    <label htmlFor="title" className="text-sm font-medium">
                      Title *
                    </label>
                    <input
                      id="title"
                      type="text"
                      placeholder="Enter post title..."
                      {...register('title', {
                        required: 'Title is required',
                        minLength: {
                          value: 5,
                          message: 'Title must be at least 5 characters',
                        },
                        maxLength: {
                          value: 100,
                          message: 'Title must be less than 100 characters',
                        },
                      })}
                      className="w-full px-3 py-2 border border-input bg-background rounded-md text-sm ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    />
                    {errors.title && (
                      <p className="text-sm text-destructive">{errors.title.message}</p>
                    )}
                    <p className="text-xs text-muted-foreground">
                      {watchedTitle.length}/100 characters
                    </p>
                  </div>

                  {/* Body */}
                  <div className="space-y-2">
                    <label htmlFor="body" className="text-sm font-medium">
                      Content *
                    </label>
                    <textarea
                      id="body"
                      rows={8}
                      placeholder="Write your post content here..."
                      {...register('body', {
                        required: 'Content is required',
                        minLength: {
                          value: 10,
                          message: 'Content must be at least 10 characters',
                        },
                        maxLength: {
                          value: 1000,
                          message: 'Content must be less than 1000 characters',
                        },
                      })}
                      className="w-full px-3 py-2 border border-input bg-background rounded-md text-sm ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 resize-none"
                    />
                    {errors.body && (
                      <p className="text-sm text-destructive">{errors.body.message}</p>
                    )}
                    <p className="text-xs text-muted-foreground">
                      {watchedBody.length}/1000 characters
                    </p>
                  </div>

                  {/* Submit Buttons */}
                  <div className="flex gap-3">
                    <Button
                      type="submit"
                      disabled={isSubmitting || createPostMutation.isPending}
                      className="flex-1"
                    >
                      {isSubmitting || createPostMutation.isPending ? 'Creating...' : 'Create Post'}
                    </Button>
                    <Button type="button" variant="outline" onClick={fillSampleData}>
                      Fill Sample
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          </div>

          {/* Preview & Info */}
          <div className="space-y-6">
            {/* Preview */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Preview</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <p className="text-sm font-medium">Title</p>
                    <p className="text-sm text-muted-foreground">
                      {watchedTitle || 'No title yet...'}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm font-medium">Content</p>
                    <p className="text-sm text-muted-foreground whitespace-pre-wrap line-clamp-6">
                      {watchedBody || 'No content yet...'}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm font-medium">Word Count</p>
                    <p className="text-sm text-muted-foreground">
                      {watchedBody ? watchedBody.split(' ').filter(word => word).length : 0} words
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Tips */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Writing Tips</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2 text-sm text-muted-foreground">
                  <p>• Use a clear, descriptive title</p>
                  <p>• Write engaging content that provides value</p>
                  <p>• Keep paragraphs short and readable</p>
                  <p>• Use bullet points for lists</p>
                  <p>• Proofread before publishing</p>
                </div>
              </CardContent>
            </Card>

            {/* Current User Info */}
            {currentUser && (
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Current User</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <p className="text-sm font-medium">{currentUser.name}</p>
                    <p className="text-xs text-muted-foreground">@{currentUser.username}</p>
                    <p className="text-xs text-muted-foreground">{currentUser.email}</p>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </Layout>
  );
} 